#include <errno.h>
#include <string.h>

#include "common.c"

char* readline(ssize_t* len) {
    char* line = 0;
    size_t size = 0;
    errno = 0;
    *len = getline(&line, &size, stdin);
    if (*len < 0) {
        if (errno == 0) {
            return 0;
        }
        perror("getline");
        exit(1);
    }
    return line;
}

bool recv_all(int sock) {
    char buf[1024];
    while (1) {
        ssize_t r = recv(sock, buf, sizeof(buf) - 1, 0);
        if (r < 0) {
            return false;
        }
        if (r == 0) {
            return true;
        }
        buf[r] = 0;
        printf("%s", buf);
        if (strchr(buf, '\n')) {
            return true;
        }
    }
}

void loop(int sock) {
    ssize_t len;
    char* line = readline(&len);
    if (!line) {
        close(sock);
        exit(0);
    }
    if (!send_all(sock, line, len)) {
        perror("send");
        exit(1);
    }
    if (!recv_all(sock)) {
        perror("recv");
        exit(1);
    }
    free(line);
}

int main() {
    struct sockaddr_in addr;
    
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0) {
        perror("socket");
        return 1;
    }
    
    bzero(&addr, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(12345);
    addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
    
    if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
        perror("connect");
        return 1;
    }
    
    while (1) loop(sock);
}
